<?php
/**
 * 広告画面コントローラー
 *
 * @package  app
 * @extends  Controller
 */
class Controller_Manage_Reward extends Controller_Manage {
	private $domain;

	/**
	 * before
	 *
	 * @access  public
	 * @return  Response
	 */
	public function before() {
		set_time_limit(180);
		// 時間制限無し
		parent::before();
		$this -> paths = explode('/', Input::uri());

		if (!empty($_SERVER["HTTPS"])) {
			$this -> domain = 'https://';
		} else {
			$this -> domain = 'http://';
		}
		$this -> domain .= $_SERVER["HTTP_HOST"];
	}

	/**
	 * index
	 *
	 * @access  public
	 * @return  Response
	 */
	public function action_index() {
		return Response::forge(View::forge('manage/reward/index'), D_HTTP_UPDATE);
	}

	/**
	 * 広告一覧
	 *
	 * @access  public
	 * @return  Response
	 */
	public function action_list() {
		$description = "";
		$post = Input::post();
		$views = array();

		$action = isset($post['action']) ? $post['action'] : '';

		// 広告追加
		if ($action == 'add') {
			unset($post['action']);
			try {
				$query = DB::select(DB::expr('COUNT(*) as count'));
				$query -> from('reward_view');
				$query -> where('ad_company', $post['ad_company']);
				$query -> where('ad_id', $post['ad_id']);
				$result = $query -> execute() -> as_array();
				if( $result[0]['count'] == 0 ) {
					$query = DB::insert('reward_view');
					$query -> set($post);
					$query -> execute();
				} else {
					$post['del'] = 0;
					$query = DB::update('reward_view');
					$query -> set( $post );
					$query -> where('ad_company', $post['ad_company']);
					$query -> where('ad_id', $post['ad_id']);
					$query -> execute();
				}
			} catch (\Exception $e) {
				$views['error'] = '登録/更新に失敗しました ' . $e->getMessage();
			}
		}

		// 変更
		if ($action == 'edit') {
			unset($post['action']);
			$query = DB::update('reward_view');
			$query -> where('reward_id', $post['reward_id']);
			unset($post['reward_id']);
			$query -> set( $post );
			$query -> execute();
		}

		// 広告削除
		if ($action == 'delete') {
			$query = DB::update('reward_view');
			$query -> set(array('del' => '1'));
			$query -> where('reward_id', $post['reward_id']);
			$query -> execute();
		}

		// 一覧取得
		$query = DB::select('*');
		$query -> from('reward_view');
		$query -> where('del', '0');
		$query -> order_by('score', 'DESC');
		$query -> order_by('create_date', 'DESC');
		$query -> order_by('point', 'DESC');
		$list = $query -> execute() -> as_array();
		foreach ($list as $key => $value) {
			$list[$key]['詳細'] = sprintf('%s/manage/reward/detail/%d/', $this -> domain, $list[$key]['reward_id']);
		}
		foreach ($list as $key => $value) {
			$list[$key]['削除'] = sprintf('%s/manage/reward/delete/%d/', $this -> domain, $list[$key]['reward_id']);
		}

		//
		$csv = Input::get('csv');
		if (empty($csv)) {
			$views['list'] = $list;
			
			return Response::forge(View::forge('manage/reward/list', $views), D_HTTP_UPDATE);
		} else {
			$views['list'] = array();
			foreach( $list as $l ) {
				$views['list'][] = array(
					'事業者' => $l['ad_company'],
					'広告ID' => $l['ad_id'],
					'取得日' => $l['post_date'],
					'報酬' => $l['payment'],
					'ポイント' => $l['point'],
					'アイコン' => $l['icon'],
					'タイトル' => $l['title'],
					'簡易獲得条件' => $l['subtitle'],
					'獲得条件' => $l['advertisement'],
					'注意事項' => $l['notice'],
					'アプリ説明' => $l['description'],
					'優先度' => $l['score'],
					'カテゴリ' => $l['category'],
				);
			}
			
			return Response::forge(View::forge('manage/csv', $views), D_HTTP_UPDATE);
		}
	}

	/**
	 * 入力
	 *
	 * @access  public
	 * @return  Response
	 */
	public function action_input() {
		$post = Input::post();

		$views = array();
		$views['reward_id'] = '';
		if (isset($post['reward_id'])) {
			// リクエスト
			$query = DB::select('*');
			$query -> from('reward_view');
			$query -> where('reward_id', $post['reward_id']);
			$result = $query -> execute() -> as_array();
			$views['detail'] = $result[0];
		}

		return Response::forge(View::forge('manage/reward/input', $views), D_HTTP_UPDATE);
	}

	/**
	 * 広告追加
	 *
	 * @access  public
	 * @return  Response
	 */
	public function action_api() {
		$post = Input::post();
		$views = array();
		$company = $this -> paths[3];

		// 案件取得
		$list = $this->reward_api2view($company);
		usort($list, 'reward_sort');
		$views['list'] = $list;

		// 追加済み案件
		$query = DB::select('ad_company', 'ad_id');
		$query -> from('reward_view');
		$query -> where('del', '0');
		$result = $query -> execute() -> as_array();
		$r = array();
		foreach( $result as $k => $v ) {
			$r[ $v['ad_company'] . $v['ad_id'] ] = 1;
		}
		foreach( $views['list'] as $k => $v) {
			if( isset($r[ $v['ad_company'] . $v['ad_id'] ] ) ) {
				$views['list'][$k]['added'] = 1;
			}
		}
		
		//
		$csv = Input::get('csv');
		if (empty($csv)) {
			return Response::forge(View::forge('manage/reward/api', $views), D_HTTP_UPDATE);
		} else {
			return Response::forge(View::forge('manage/reward/api_csv', $views), D_HTTP_UPDATE);
		}
	}

	/**
	 * 取得案件一覧
	 *
	 * @access  public
	 * @return  Response
	 */
	public function action_apilist() {
		$views = array();

		// 案件取得
		$list = $this->reward_api2view();
		usort($list, 'reward_sort');
		
		//
		$csv = Input::get('csv');
		if (empty($csv)) {
			$views['description'] = '件数が多いため優先度上位300件のみ表示しています。CSVは全件出力されます';
			$views['list'] = array_slice($list, 0, 300);
			
			return Response::forge(View::forge('manage/reward/api', $views), D_HTTP_UPDATE);
			
		} else {
			$views['list'] = array();
			foreach( $list as $l ) {
				$views['list'][] = array(
					'事業者' => $l['ad_company'],
					'広告ID' => $l['ad_id'],
					'取得日' => $l['post_date'],
					'報酬' => $l['payment'],
					'ポイント' => $l['point'],
					'アイコン' => $l['icon'],
					'タイトル' => $l['title'],
					'簡易獲得条件' => $l['subtitle'],
					'獲得条件' => $l['advertisement'],
					'注意事項' => $l['notice'],
					'アプリ説明' => $l['description'],
					'優先度' => $l['score'],
					'カテゴリ' => $l['category'],
				);
			}
			
			return Response::forge(View::forge('manage/csv', $views), D_HTTP_UPDATE);
		}
	}

	/**
	 * リワード売上
	 *
	 * @access  public
	 * @return  Response
	 */
	public function action_payment() {
		$description = '';
		$list = array();
		
		for( $i = 0; $i < 31; $i ++) {
			$col = array();

			switch( $this->paths[3] ) {
				case 'daily':
					$day = 60 * 60 * 24;
					$max = mktime(0,0,0,date("m"),date("d"),date("Y")) - ($i - 1) * $day;
					$min = $max - $day;
					$col['日付'] = date('Y/m/d', $min);
					break;
				case 'monthly':
					$max = mktime(0,0,0,date("m")-$i+1,1,date("Y"));
					$min = mktime(0,0,0,date("m")-$i  ,1,date("Y"));
					$col['日付'] = date('Y/m', $min);
					break;
			}
			
			// ポイント流通
			$query = DB::select(DB::expr("ad_company AS 事業者"), DB::expr("ad_id AS 広告ID"), DB::expr("COUNT(*) AS 件数"), DB::expr("SUM(point_value) AS ポイント合計"), DB::expr("SUM(payment) AS 売上合計"));
			$query -> from('member_point');
			$query -> where('member_point.reward_id', '>',  0);
			$query -> where('member_point.create_date', '<',  date('Y-m-d', $max));
			$query -> where('member_point.create_date', '>=', date('Y-m-d',$min));
			$query -> join('reward_view','LEFT') -> on('reward_view.reward_id', '=', 'member_point.reward_id');
			$query -> group_by('ad_company','ad_id');
                        $query -> order_by('ad_company');
			$query -> order_by('ad_id');
			$result = $query -> execute() -> as_array();
			
			foreach($result as $value) {
				$list[] = array_merge($col, $value);
			}
		}

		$csv = Input::get('csv');
		if( empty($csv)) {
			$description = '自社ウォール版アプリからの成果のみ計測しています';
			return Response::forge(View::forge('manage/table',array('description'=>$description,'list' => $list)), D_HTTP_UPDATE);
		} else {
			return Response::forge(View::forge('manage/csv',array('description'=>$description,'list' => $list)), D_HTTP_UPDATE);
		}
	}
}
function reward_sort($a, $b)
{
    if ($a['score'] == $b['score']) {
 	    return ($a['ad_id'] > $b['ad_id']) ? -1 : 1;
    }
    return ($a['score'] > $b['score']) ? -1 : 1;
}


